// import * as echarts from '../../../../packages/ec-canvas/echarts';
import * as echarts from '../../packages/ec-canvas/echarts';
// var util = require('../../../../utils/public');
var util = require('../../utils/public');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //图表
    index:0,
    title:'血压',//string
    yname:'mmHg',//纵坐标
    legend:[],//['肌酐','尿蛋白']
    xData:[],//[1,2,3]
    data_cur1:[],//
    data_cur:[],//
    data_his1:[],//
    data_his:[],//
    //请求的数据
    pressure1:[],
    pressure2:[],
    sugar:[],
    fat:[],
    uricProtein:[],
    uricGravity:[],
    uricpH:[],
    uricVolume:[],
    creatinine:[],
    ///echart
    ecLine1:{
      lazyLoad: true
    },
    ecLine2:{
      lazyLoad: true
    },
    ecLine3:{
      lazyLoad: true
    },
    ecLine4:{
      lazyLoad: true
    },
    ecLine5:{
      lazyLoad: true
    },
    ecLine6:{
      lazyLoad: true
    },
    ecLine7:{
      lazyLoad: true
    },
  },
methods:{
  //1.初始化所有数据
  initData:async function(that){
    await getRecords(that)//初始化数值
    that.methods.initBloodPressure(that)
    that.methods.initBloodSugar(that)
    that.methods.initUricProtein(that)
    that.methods.initUricGravity(that)
    that.methods.initUricpH(that)
    that.methods.initUricVolume(that)
    that.methods.initCreatinine(that)
  },
  //1.血压
  initBloodPressure:async function(that){
    var _cur = that.data.pressure1//data_cur
    var _his = that.data.pressure2//data_his
    var _xData = getxAxisFromToday()//xData
    var legend = ['收缩压','舒张压']
    var yname='mmHg'
    //init
    that.ecComponent = that.selectComponent('#mychart1');
    that.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      getOption(chart,that,_cur,_his,_xData,legend,yname);
      return chart;
    });
  },
  //2.血糖
  initBloodSugar:async function(that){
    var _cur = that.data.sugar
    var _xData = getxAxisFromToday()
    var legend=['血糖']
    var yname='mmol/L'
    that.ecComponent = that.selectComponent('#mychart2');
    that.ecComponent.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      getOption2(chart,that,_cur,_xData,legend,yname);
      return chart;
    });
  },
  //3.尿蛋白
  initUricProtein:async function(that){
    var _cur = that.data.uricProtein
    var _xData = getxAxisFromToday()
    var legend=['尿蛋白']
    var yname='mg'
    //init
    that.ecComponent = that.selectComponent('#mychart3');
    that.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      getOption2(chart,that,_cur,_xData,legend,yname);
      return chart;
    });
  },
  //4.尿比重
  initUricGravity:async function(that){
    var _cur = that.data.uricGravity
    var _xData = getxAxisFromToday()
    var legend=['尿比重']
    var yname=''
    //init
    that.ecComponent = that.selectComponent('#mychart4');
    that.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      getOption2(chart,that,_cur,_xData,legend,yname);
      return chart;
    });
  },
  //5.尿ph
  initUricpH:async function(that){
    var _cur = that.data.uricpH
    var _xData = getxAxisFromToday()
    var legend=['尿pH']
    var yname=''
    //init
    that.ecComponent = that.selectComponent('#mychart5');
    that.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      getOption2(chart,that,_cur,_xData,legend,yname);
      return chart;
    });
  },
  //6.尿量
  initUricVolume:async function(that){
    var _cur = that.data.uricVolume
    var _xData = getxAxisFromToday()
    var legend=['尿量']
    var yname='ml'
    //init
    that.ecComponent = that.selectComponent('#mychart6');
    that.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      getOption2(chart,that,_cur,_xData,legend,yname);
      return chart;
    });
  },
  //7.肌酐
  initCreatinine:async function(that){
    var _cur = that.data.creatinine
    var _xData = getxAxisFromToday()
    var legend=['肌酐']
    var yname='μmol/L'
    //init
    that.ecComponent = that.selectComponent('#mychart7');
    that.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      getOption2(chart,that,_cur,_xData,legend,yname);
      return chart;
    });
  },
  test(){
    console.log(this)
    console.log(this.selectComponent('#test'))
  }
},
test(){
  console.log(this)
  console.log(this.selectComponent('#test'))
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this
    console.log(this)
    setTimeout(function () {
      console.log(that.selectComponent('#test'))
    }, 3000)
    var that = this
    console.log(that)
    that.methods.initData(that)
    // that.__proto__.initData(that)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

})
function getOption2(chart,that,_cur,_xData,legend,yname) {
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    backgroundColor: "#fff",
    color: ['#37A2DA','#67E0e3','#9FE6B8'],
    legend: {
      data: legend,
      top: 10,
      left: 'center',
      // backgroundColor: 'red',
      z: 100
    },
    grid: {
      top:"25%",
      left: "10%",
      right: "10%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: 'category',
      // boundaryGap: false,
      data: _xData.reverse()||[],
      axisLabel: {
        interval: 0,
        rotate: 20
      },
    },
    yAxis: {
      x: 'center',
      name: yname,
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: legend[0],
      type: 'line',
      symbolSize: 3,
      smooth:true,
      data: _cur.reverse()||[],
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: 'Avg' }]
      }
    },
  ]
  };
  chart.setOption(option);
}
function getOption(chart,that,_cur,_his,_xData,legend,yname){
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    backgroundColor: "#fff",
    color: ['#37A2DA','#67E0e3','#9FE6B8'],
    legend: {
      data: legend,
      top: 10,
      left: 'center',
      // backgroundColor: 'red',
      z: 100
    },
    grid: {
      top:"25%",
      left: "10%",
      right: "10%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: _xData.reverse()||[],
      axisLabel: {
        interval: 0,
        rotate: 20
    },
    },
    yAxis: {
      x: 'center',
      name: yname,
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    
    series: [{
      name: legend[0],
      type: 'line',
      symbolSize: 3,
      smooth:true,
      data: _cur.reverse()||[],
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: 'Avg' }]
      }
    },{
        name: legend[1],
        type: 'line',
        symbolSize: 3,
        smooth: true,
        data: _his.reverse()||[],
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: 'Avg' }]
        }
    }
  ]
  };
  chart.setOption(option);
}
function gettimeStamp(days){
  var timestamp = Date.parse(new Date());
  var before_timetamp = timestamp*0.001 - 24 * 60 * 60 * days;
  return before_timetamp
}
function getxAxisFromToday(){
  var xAxis=[]
  for(var i = 0;i < 7;i++){
    xAxis.push(util.getMyDateWithoutYear(gettimeStamp(i)))
  }
  return xAxis
}
async function getRecords(that){
  var that = that
  console.log(that)
  //血压
  var pressure1=[]
  var pressure2=[]
  //血糖，血脂
  var sugar=[]
  var fat=[]
  //尿蛋白，尿比重,尿ph,尿量
  var uricProtein=[]
  var uricGravity=[]
  var uricpH=[]
  var uricVolume=[]
  //肌酐
  var creatinine=[]
  for(var i = 0;i<7;i++){
    var year = new Date(gettimeStamp(i)*1000).getFullYear()
    var month = new Date(gettimeStamp(i)*1000).getMonth() + 1
    var day = new Date(gettimeStamp(i)*1000).getDate()
    var _date={year,month,day}
    var records = await getDakaRecords(that,_date)
    if(records==null){
      pressure1.push(null)
      pressure2.push(null)
      sugar.push(null)
      fat.push(null)
      uricProtein.push(null)
      uricGravity.push(null)
      uricpH.push(null)
      uricVolume.push(null)
      creatinine.push(null)
    }else{
      //pressure1
      if(records._bloodPressure1!=null&&records._bloodPressure1.length>0)
      pressure1.push(parseFloat(records._bloodPressure1))
      else
      pressure1.push(null)
      //pressure2
      if(records._bloodPressure2!=null&&records._bloodPressure2.length>0)
      pressure2.push(parseFloat(records._bloodPressure2))
      else
      pressure2.push(null)
      //sugar
      if(records._bloodSugar!=null&&records._bloodSugar.length>0)
      sugar.push(parseFloat(records._bloodSugar))
      else
      sugar.push(null)
      //fat
      if(records._bloodFat!=null&&records._bloodFat.length>0)
      fat.push(parseFloat(records._bloodFat))
      else
      fat.push(null)
      //_uricProtein
      if(records._uricProtein!=null&&records._uricProtein.length>0)
      uricProtein.push(parseFloat(records._uricProtein))
      else
      uricProtein.push(null)
      //_uricGravity
      if(records._uricGravity!=null&&records._uricGravity.length>0)
      uricGravity.push(parseFloat(records._uricGravity))
      else
      uricGravity.push(null)
      //_uricpH
      if(records._uricpH!=null&&records._uricpH.length>0)
      uricpH.push(parseFloat(records._uricpH))
      else
      uricpH.push(null)
      //_uricVolume
      if(records._uricVolume!=null&&records._uricVolume.length>0)
      uricVolume.push(parseFloat(records._uricVolume))
      else
      uricVolume.push(null)
      //_creatinine
      if(records._creatinine!=null&&records._creatinine.length>0)
      creatinine.push(parseFloat(records._creatinine))
      else
      creatinine.push(null)
    }
  }
  that.setData({
    pressure1:pressure1,
    pressure2:pressure2,
    sugar:sugar,
    fat:fat,
    uricProtein:uricProtein,
    uricGravity:uricGravity,
    uricpH:uricpH,
    uricVolume:uricVolume,
    creatinine:creatinine
  })
  console.log(that.data.pressure1)
  console.log(that.data.pressure2)
  console.log(that.data.sugar)
  console.log(that.data.fat)
  console.log(that.data.uricProtein)
  console.log(that.data.uricGravity)
  console.log(that.data.uricpH)
  console.log(that.data.uricVolume)
  console.log(that.data.creatinine)
  //获取全部records匹配同一天，找到其他数据
  // console.log(detailPage)
}
async function getBloodPressure(){
  var that = this
  var pressure=[]
  for(var i = 0;i<7;i++){
    var year = new Date(gettimeStamp(i)*1000).getFullYear()
    var month = new Date(gettimeStamp(i)*1000).getMonth() + 1
    var day = new Date(gettimeStamp(i)*1000).getDate()
    var _date={year,month,day}
    var records = await getDakaRecords(that,_date)
    if(records==null){
      pressure.push(null)
    }else{
      pressure.push(parseFloat(records._bloodPressure1))
    }
  }
  return pressure
  //获取全部records匹配同一天，找到其他数据
  // console.log(detailPage)
}
async function getBloodPressure2(){
  var that = this
  var pressure=[]
  for(var i = 0;i<7;i++){
    var year = new Date(gettimeStamp(i)*1000).getFullYear()
    var month = new Date(gettimeStamp(i)*1000).getMonth() + 1
    var day = new Date(gettimeStamp(i)*1000).getDate()
    var _date={year,month,day}
    var records = await getDakaRecords(that,_date)
    if(records==null){
      pressure.push(null)
    }else{
      pressure.push(parseFloat(records._bloodPressure2))
    }
  }
  console.log(pressure)
  return pressure
  //获取全部records匹配同一天，找到其他数据
  // console.log(detailPage)
}
function compareDay(_date,r){
  for(var i = 0;i<r.length;i++){
    if(_date.year==r[i].year &&
      _date.month==r[i].month &&
      _date.day==r[i].date){
        return i
      }
  }
  return null
}
 async function getDakaRecords(that,_date){
   var records = null
   try{
  var res = await wx.cloud.callFunction({
    name:'clockIn',
    data:{
      type:"getRecords",
      openid:wx.getStorageSync('openid')
    }
  });
  var tempRecords = res.result.records
      //获取日期数组，匹配index获取其他数据
      const r = tempRecords.map(item=>{
        var tempDate =new Date(item._date);
        return {
          year: tempDate.getFullYear(),
          month:tempDate.getMonth()+1,
          date:tempDate.getDate()
        }
      })
      var index = compareDay(_date,r)
      records = tempRecords[index]
}catch(error){
  return null;
  } 
  return records
  
}
async function determinValue1(){
  var pressure1_cur = await getBloodPressure()
  return {
    onInit: function (canvas, width, height,dpr){
      console.log()
      //初始化echarts元素，绑定到全局变量，方便更改数据
      chartLine1 = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
      });
      canvas.setChart(chartLine1);

      //可以先不setOption，等数据加载好后赋值，
      //不过那样没setOption前，echats元素是一片空白，体验不好，所有我先set。
      var xData = getxAxisFromToday()  // x轴数据 自己写
      // var xData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      var title = "血压"
      var legend = ['舒张压','收缩压']  
      var data_cur = _cur
      var option = getOption(title,legend,xData,data_cur);
      chartLine1.setOption(option);
  },
  }
}